﻿package com.vinyl.controls
{
	import flash.events.*;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.display.MovieClip;
	import com.vinyl.controls.ButtonView;

	public class Button extends EventDispatcher
	{
		public static var EVENT_CHANGED: String = 'button_changed';
		
		public var groupName: String;
		public var view: ButtonView;
		private var value: Boolean;
		private var enabled: Boolean;
		
		function Button( view: ButtonView, value: Boolean )
		{
			this.view = view;
			
			setValue( value );
			setEnabled( true );
		}
		
		public function setMouseEvent( obj: Object ): void
		{
		}
		
		public function setEnabled( enable: Boolean ): void
		{
			if( enabled == enable ) return;
			switch( enable )
			{
				case true:
					view.buttonMode  = true;
					view.addEventListener( MouseEvent.ROLL_OVER, handler );
					view.addEventListener( MouseEvent.ROLL_OUT, handler );
					view.addEventListener( MouseEvent.CLICK, handler );
					break;
				
				case false:
					view.removeEventListener( MouseEvent.ROLL_OVER, handler );
					view.removeEventListener( MouseEvent.ROLL_OUT, handler );
					view.removeEventListener( MouseEvent.CLICK, handler );
					break;
			}
			
			enabled = enable;		
		}
		
		private function handler( e ):void
		{
			switch( e.type )
			{
				case "rollOver":
					view["setState"]( value ? ButtonView.ACTIVE_OVER : ButtonView.NORMAL_OVER );
				break;
				case "rollOut":
					view["setState"]( value ? ButtonView.ACTIVE_UP : ButtonView.NORMAL_UP );
				break;
				case "click":
					setValue( !value );
				break;
			}
		}
		
		public function setValue( newValue: Boolean ): void
		{
			value = newValue;
			view["setState"]( value ? ButtonView.ACTIVE_UP : ButtonView.NORMAL_UP );
			
			if( enabled ) 
			{
				dispatchEvent( new Event( EVENT_CHANGED ) );
			}
		}
		
		public function getValue(): Boolean
		{
			return value;
		}
	}
}

